package com.student_system.students.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.student_system.common.Result;
import com.student_system.students.entity.Course;
import com.student_system.students.service.ICourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/courses")
public class CourseController {
    @Autowired
    private ICourseService courseService;

    @GetMapping("/getAll")
    public Result.ResultData<Map<String, Object>> getCoursesByPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String courseName) {

        Page<Course> page = new Page<>(current, size);
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(courseName)) {
            queryWrapper.like("course_name", courseName);
        }
        queryWrapper.orderByAsc("course_no");

        Page<Course> result = courseService.page(page, queryWrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.getRecords());
        data.put("total", result.getTotal());
        data.put("size", result.getSize());
        data.put("current", result.getCurrent());
        data.put("pages", result.getPages());

        return Result.success(data);
    }

    @GetMapping("/{courseNo}")
    public Result.ResultData<Course> getCourse(@PathVariable Integer courseNo) {
        Course course = courseService.getById(courseNo);
        if (course == null) {
            return Result.error("404", "课程不存在");
        }
        return Result.success(course);
    }

    @PostMapping
    public Result.ResultData<String> saveCourse(@RequestBody Course course) {
        try {
            if (courseService.save(course)) {
                return Result.success("保存成功");
            }
            return Result.error("500", "保存课程失败");
        } catch (Exception e) {
            return Result.error("500", "保存课程时发生错误: " + e.getMessage());
        }
    }

    @DeleteMapping("/{courseNo}")
    public Result.ResultData<String> deleteCourse(@PathVariable Integer courseNo) {
        try {
            if (courseService.removeById(courseNo)) {
                return Result.success("删除成功");
            }
            return Result.error("500", "删除课程失败");
        } catch (Exception e) {
            return Result.error("500", "删除课程时发生错误: " + e.getMessage());
        }
    }

    @PutMapping("/{courseNo}")
    public Result.ResultData<String> updateCourse(
            @PathVariable Integer courseNo,
            @RequestBody Course course) {
        try {
            Course existingCourse = courseService.getById(courseNo);
            if (existingCourse == null) {
                return Result.error("404", "课程不存在");
            }

            // 只更新传入的字段
            if (course.getCourseName() != null) {
                existingCourse.setCourseName(course.getCourseName());
            }
            if (course.getCredit() != null) {
                existingCourse.setCredit(course.getCredit());
            }
            if (course.getTeacherNo() != null) {
                existingCourse.setTeacherNo(course.getTeacherNo());
            }

            if (courseService.updateById(existingCourse)) {
                return Result.success("课程更新成功");
            }
            return Result.error("500", "课程更新失败");
        } catch (Exception e) {
            return Result.error("500", "更新课程时发生错误: " + e.getMessage());
        }
    }

    @GetMapping("/getByTeacher/{teacherNo}")
    public Result.ResultData<List<Course>> getCoursesByTeacher(@PathVariable Integer teacherNo) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_no", teacherNo);
        List<Course> courses = courseService.list(queryWrapper);
        return Result.success(courses);
    }

    @GetMapping("/getAllCourse")
    public Result.ResultData<List<Course>> getAllCourse() {
        try {
            List<Course> courseList = courseService.list();
            return Result.success(courseList);
        } catch (Exception e) {
            return Result.error("500", "获取课程列表时发生错误: " + e.getMessage());
        }
    }
}